package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserLoginService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api("用户相关接口")
@RestController
@RequestMapping("/user/user")
@Slf4j
public class UserController {
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private JwtProperties jwtProperties;

    @ApiOperation("小程序登录")
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        // 1.调用service的登录方法，获取
        User userInfo = userLoginService.login(userLoginDTO);

        // 2.如果登录成功，生成令牌jwt
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userInfo.getId());
        String jwt = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims
        );

        // 3.构造UserLoginVO对象，返回Result
        UserLoginVO userLoginResult = UserLoginVO.builder().openid(userInfo.getOpenid()).token(jwt).id(userInfo.getId()).build();


        return Result.success(userLoginResult);
    }
}
